package com.mini.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.mini.config.SendConfig;
import com.mini.domain.PushBody;
import com.mini.enums.YesOrNoEnum;
import com.mini.redis.RedisCache;
import com.mini.service.IMsgSendService;
import com.mini.service.IMsgService;
import com.mini.service.IWebSocketService;
import com.mini.util.ChannelUtils;
import com.mini.ws.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
public class WebSocketServiceImpl implements IWebSocketService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IMsgService msgService;
    @Autowired
    private IMsgSendService msgSendService;
    @Autowired
    private SendConfig sendConfig;

    @Transactional
    public void sendMessage(List<String> channels, String content) {

        for (String channel : channels) {
            msgService.create(channel, content);
        }

        Set<String> userIds = ChannelUtils.getChannel(channels);

        for (String userId : userIds) {

            long loginId = Long.parseLong(userId);

            Long sendId = IdUtil.getSnowflake().nextId();

            if (YesOrNoEnum.YES.equals(sendConfig.getSaveSendRecords())) {
                sendId = msgSendService.create(loginId, channels);
            }

            PushBody body = new PushBody()
                    .setSendId(sendId)
                    .setChannels(channels)
                    .setContent(content)
                    .setSendTime(DateUtil.now());

            boolean b = MyWebSocketHandler.sendMessage(loginId, JSONUtil.toJsonStr(body));

            if (YesOrNoEnum.YES.equals(sendConfig.getSaveSendRecords()) && b) {
                msgSendService.sended(sendId);
            }
        }

    }

    /**
     * 获取在线用户数
     *
     * @return
     */
    public Long getOnlineSize() {

        return redisCache.countKeys(ChannelUtils.getUserKeys());
    }

    @Override
    public Long getWebSocketConnectionSize() {
        return MyWebSocketHandler.getConnectionSize();
    }

    /**
     * 获取频道数量
     *
     * @return
     */
    public Long getChannelSize() {

        return redisCache.countKeys(ChannelUtils.getChannelKeys());
    }


}
